<?php
$ip = '127.0.0.1';
$port = 1935;
$pdo = new PDO(
	'mysql:host=localhost;dbname=12', 
	'root', 'root',
	array(
		PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED,
		PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES'utf8mb4';"
	)
);
/*
 +-------------------------------
 *    @socket通信整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_bind
 *    @socket_listen
 *    @socket_accept
 *    @socket_read
 *    @socket_write
 *    @socket_close
 +--------------------------------
 */

/*----------------    以下操作都是手册上的    -------------------*/
if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
    echo "socket_create ERROR:".socket_strerror($sock)."\n";
}

if(($ret = socket_bind($sock,$ip,$port)) < 0) {
    echo "socket_bind ERROR:".socket_strerror($ret)."\n";
}

if(($ret = socket_listen($sock,4)) < 0) {
    echo "socket_listen ERROR:".socket_strerror($ret)."\n";
}

$count = 0;

do {
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
        break;
    } else {
    	try {
    		$buf = @socket_read($msgsock,8192);
	        $talkback = "Client:$buf\n";
	        echo $talkback;
	        $msg = json_encode($pdo->query($buf)->fetchAll());
	        echo "Server:$msg\r\n";
	        @socket_write($msgsock, $msg, strlen($msg));
    	} catch (Exception $e) {
    		
    	}
       
    }
    socket_close($msgsock);
} while (true);
socket_close($sock);